#-*- coding:utf-8 -*-

import struct, sys, os, time
from .ip2Region import Ip2Region
import mongoengine
from log import log
from config import config
#搜索

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class SearchIp(metaclass=Singleton):
    def __init__(self):
        try:
            dbpath = os.path.abspath("./utils/ip/ip2region.db")
            self.search = Ip2Region(dbpath)
        except IOError:
            log.error("err connect db",IOError.errno)
        else:
            log.info("db connect success")

    def getSession(self):
        return self.search
    def searchCity(self,ip):
        try:
            if self.getSession().isip(ip):
                city =  self.getSession().btreeSearch(ip=ip).get("region").decode("utf-8")
            else:
                city = "火星"
        except IOError:
            log.error(IOError)
            city = "火星"
            return city
        else:
            return city
    def close(self):
        self.search.close()